package com.hgy.plugin.rest.servlet;

import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;

import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.transport.servlet.CXFNonSpringServlet;

import com.hgy.common.utils.CollectionUtil;
import com.hgy.common.utils.StringUtil;
import com.hgy.framework.helper.ClassHelper;
import com.hgy.plugin.rest.RestConstant;
import com.hgy.plugin.rest.annotation.Rest;
import com.hgy.plugin.rest.helper.RestHelper;

/**
 * REST Servlet
 * 
 * @author alone
 *
 */
@WebServlet(urlPatterns = RestConstant.SERVER_URL, loadOnStartup=0)
public class RestServlet extends CXFNonSpringServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void loadBus(ServletConfig sc) {
		//初始化 CXF 总线
		super.loadBus(sc);
		Bus bus = getBus();
		BusFactory.setDefaultBus(bus);
		publishService();
	}

	/**
	 * 发布 REST 服务
	 * 
	 */
	private void publishService() {

		Set<Class<?>> restClassSet = ClassHelper.getClassSetByAnnotation(Rest.class);
		if(CollectionUtil.isNotEmpty(restClassSet)){
			for (Class<?> restClass : restClassSet) {
				String address = getAddress(restClass);
				RestHelper.publishService(address, restClass);
			}
		}
	}

	/**
	 * 获取wsdl地址(即注解类服务名)
	 * 
	 * @param restClass
	 * @return
	 */
	private String getAddress(Class<?> restClass) {
		String address;
		
		String value = restClass.getAnnotation(Rest.class).value();
		if(StringUtil.isNotEmpty(value)){
			address = value;
		}else{
			address = restClass.getSimpleName();
		}
		//确保前面只有一个 /
		if(!address.startsWith("/")){
			address = "/" + address + "/";
		}
		address = address.replaceAll("\\/+", "/");
		return address;
	}
	
}
